package org.geektimes.projects.user.web.controller;

import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.service.UserService;
import org.geektimes.projects.user.validator.bean.validation.DelegatingValidator;
import org.geektimes.web.mvc.controller.PageController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Path("/register")
public class UserRegisterController implements PageController {

    @Resource(name = "bean/UserService")
    private UserService userService;
//    @Resource(name = "bean/Validator")
//    private DelegatingValidator validator;

    public UserRegisterController() {
    }

    /**
     * @param request  HTTP 请求
     * @param response HTTP 相应
     * @return 视图地址路径
     * @throws Throwable 异常发生时
     */
    @POST
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        User user = new User();
        user.setName(request.getParameter("name"));
        user.setEmail(request.getParameter("email"));
        user.setPassword(request.getParameter("password"));
        user.setPhoneNumber(request.getParameter("phoneNumber"));

//        Set<ConstraintViolation<User>> constraintViolations = validator.validate(user);
//        if (!constraintViolations.isEmpty()) {
//            List<String> violationErrors = constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
//            request.setAttribute("registerErrors", violationErrors);
//        } else {
//            try {
//                boolean registerResult = userService.register(user);
//                request.setAttribute("registerResult", registerResult);
//            } catch (Exception e) {
//                request.setAttribute("registerErrors", Stream.of("注册失败," + e.getMessage()).collect(Collectors.toList()));
//                request.setAttribute("registerResult", false);
//            }
//        }
        getAllUserList(request);

        return "register-success.jsp";
    }

    private void getAllUserList(HttpServletRequest request) {
        List<User> users = userService.findAll();
        request.setAttribute("users", users);
    }
}
